package JackSu.project_model.singletom;

import java.io.Serializable;

public class Singleton implements Serializable {

    // 懒汉式
    private volatile static Singleton singleton = null;

    private Singleton() {}

    public static Singleton getLazySingleton() {
        if(singleton == null) {
            synchronized (Singleton.class) {
                if(singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

    // 饿汉式
    private static Singleton hungrySingleton = new Singleton();

    public static Singleton getHungrySingleton() {
        return hungrySingleton;
    }

    // 静态内部类
    private static class SingletonFactory {
        private static Singleton singleton = new Singleton();
    }

    public static Singleton getFactorySingleton() {
        return SingletonFactory.singleton;
    }

    /* 如果该对象被用于序列化，可以保证对象在序列化前后保持一致 */
    public Object readResolve() {
        return getFactorySingleton();
    }

    // 枚举 最佳单例模式
    public enum SingletonEnum {
        SINGLETON;

        public String getName() {
            return "这是一个最佳的单例模式";
        }
    }
}
